package com.ssm.service.impl;

import com.ssm.dao.UserDao;
import com.ssm.pojo.User;
import com.ssm.service.UserService;
import com.ssm.util.MD5andKL;
import com.ssm.util.TransUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserDao userDao;
	
	public List<User> get(User user) throws Exception {

		return userDao.finUser(user);
	}

	@Override
	public Map<String, Object> addUser(User user) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		user.setId(String.valueOf(UUID.randomUUID()));
		MD5andKL.KL(user.getPassword());
		int i=userDao.addUser(user);
		if(i>0){
			map.put("code", "0000");
			map.put("msg", "add成功");
			map.put("data", i);
		}else{
			map.put("code", "0000");
			map.put("msg", "fail");
			map.put("data", "");
		}
		
		return map;
	}

	@Override
	public Map<String, Object> deleteUser(User user) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int i=userDao.deleteUser(user);
		if(i>0){
			map.put("code", "0000");
			map.put("msg", "删除成功");
			map.put("data", i);
		}else{
			map.put("code", "0001");
			map.put("msg", "fail");
			map.put("data", "");
		}
		
		return map;
	}

	@Override
	public Map<String, Object> updateUser(User user) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		int i=userDao.updateUser(user);
		if(i>0){
			map.put("code", "0000");
			map.put("msg", "更新成功");
			map.put("data", i);
		}else{
			map.put("code", "0000");
			map.put("msg", "fail");
			map.put("data", "");
		}
		return map;
	}

	@Override
	//@Cacheable(value="common" ,key="#user.id")
	public Map<String, Object> getUser(User user) throws Exception {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if (!(user.getPageCount() == null && user.getNum() == null)) {
			user.setBeginRow((user.getNum() - 1) * user.getPageCount());
		} else {
			user.setBeginRow(0);
			user.setPageCount(10);

		}
		List<User> resultlist = (List<User>) userDao.getUser(user);
		
		List<Map<String, Object>> returnlist = new ArrayList<Map<String, Object>>();
		if (resultlist.size() == 0) {
			map.put("code", "0001");
			map.put("msg", "没有用户信息！");
			map.put("data", "");
		} else {
			for(User userInfo:resultlist){
				Map<String, Object> mapUser=TransUtil.transBean2Map(userInfo);
				returnlist.add(mapUser);
			}
			map.put("code", "0000");
			map.put("msg", "查询用户信息成功");
			map.put("data", returnlist);	
		}
		return map;
	}

	@Override
	public List <User> getAll() throws Exception {
		return userDao.getAll();
	}

	@Override
	public User queryByUserName(String name) throws Exception {
		return userDao.queryByUserName(name);
	}
}